﻿using AutoMapper;
using IntelligentAgriculture.Contracts.Dto.Output;
using IntelligentAgriculture.Contracts.Interface;
using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.WebAPI.Application.Command.VendorModelCommand;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;

namespace IntelligentAgriculture.WebAPI.Application.CommandHandler.VendorModelCommandHandler
{
	/// <summary>
	/// 供应商数据导出
	/// </summary>
	public class ExportCustomerCommandHandler : IRequestHandler<ExportCustomerCommand, IActionResult>
	{
		private readonly IVendorModelService _vendorModelService;
		private readonly IMapper _mapper;
		/// <summary>
		/// 构造方法
		/// </summary>
		/// <param name="vendorModelService"></param>
		public ExportCustomerCommandHandler(IVendorModelService vendorModelService, IMapper mapper)
		{
			_vendorModelService = vendorModelService;
			_mapper = mapper;
		}
		public async Task<IActionResult> Handle(ExportCustomerCommand request, CancellationToken cancellationToken)
		{
			var list = await _vendorModelService.GetVendormodel(request.InPut);
			//获取数据
			var data = list.Data;

			//转换为导出类型
			var exportCustomerDto = _mapper.Map<List<Vendormodel>, List<VendorModelminiExcelOutPut>>(data);

			// 创建一个内存流对象
			MemoryStream ms = new MemoryStream();

			// 异步将导出的客户数据保存到内存流中
			await ms.SaveAsAsync(exportCustomerDto);

			// 将内存流的读取位置重置到开始位置
			ms.Seek(0, SeekOrigin.Begin);

			// 返回一个文件流结果，指定内容类型和文件下载名
			return new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
			{
				FileDownloadName = "客户信息.xlsx"
			};


		}
	}
}
